import Script from 'react-load-script';
import React, {useEffect, useState} from 'react';
import {connect, Prompt} from 'umi';
import {Result, Alert, Spin} from 'antd';

import styles from './index.less';
import config from './onlyoffice';

let docEditor;

const OfficeComponent = (props) => {
  const {dispatch, location, adding} = props;
  const [errorMsg, setErrorMsg] = useState();

  const documentEvents = () => {
    return {
      onAppReady: (data) => console.log(data),
      onDocumentReady: (data) => console.log(data),
      onError: (data) => console.log(data),
      onSave: (data) => console.log(data),
      onRequestHistory: () => {
        dispatch({
          type: 'office/history',
          payload: {...location.query},
          callback: (res) => {
            if (res.success) {
              docEditor.refreshHistory(res.data);
            }
          },
        });
      },
      onRequestHistoryData: (event) => {
        const version = event.data;
        dispatch({
          type: 'office/historyDetail',
          payload: {...location.query, version},
          callback: (res) => {
            if (res.success) {
              docEditor.setHistoryData(res.data);
            }
          },
        });
      },
      onRequestHistoryClose: () => {
        document.location.reload();
      },
    };
  };

  useEffect(() => {
    dispatch({
      type: 'office/view',
      payload: {...location.query},
      callback: (res) => {
        if (res.success) {
          config = {...res.data, ...config};
          config.events = documentEvents();
          document.title = `${res.data.document.title} - eoffice`;
        } else {
          setErrorMsg(res.msg);
        }
      },
    });
  }, []);

  const handleScriptLoad = () => {
    docEditor = new window.DocsAPI.DocEditor(config.onlyOfficeId, config);
  };

  const handleScriptError = () => {
    setErrorMsg('Onlyoffice引擎加载失败');
  };

  const render = () => {
    console.log(adding);
    if (adding) {
      return (
        <Spin>
          <Alert key="loading" type="info" message="" description="文档加载中"/>
        </Spin>
      );
    }

    if (errorMsg === undefined) {
      <Result key="result" status="info" title={errorMsg}/>;
    }

    return (
      <>
        <Prompt message="你确定要离开么？"/>
        <Script url={config.scriptUrl} onError={handleScriptError} onLoad={handleScriptLoad}/>
      </>
    );
  };

  return (
    <>
      <div className={styles.office}>
        <div id={config.onlyOfficeId}/>
      </div>
      {render()}
    </>
  );
};

export default connect(({office, loading}) => ({
  office,
  adding: loading.effects['office/view'],
}))(OfficeComponent);
